<?php

namespace System\Core;

class Router
{
    protected $routes = [
        'GET' => [],
        'POST' => [],
    ];

    public function get($uri, $action)
    {
        $this->routes['GET'][$uri] = $action;
    }

    public function post($uri, $action)
    {
        $this->routes['POST'][$uri] = $action;
    }

    public function rule($uri, $action)
    {
        $this->routes['GET'][$uri] = $action;
        $this->routes['POST'][$uri] = $action;
    }

    public function dispatch(Request $request)
    {
        $method = $request->method();
        $uri = $request->uri();

        if (isset($this->routes[$method][$uri])) {
            $action = $this->routes[$method][$uri];
            return $this->callAction($action);
        }

        // 尝试匹配动态路由
        foreach ($this->routes[$method] as $route => $action) {
            // 简单动态路由：如 /user/{id}
            $pattern = '#^' . preg_replace('/\{(\w+)\}/', '([^/]+)', $route) . '$#';

            if (preg_match($pattern, $uri, $matches)) {
                array_shift($matches); // 移除完整匹配
                return $this->callAction($action, $matches);
            }
        }

        // 未找到路由
        return new Response('Page not found', 404);
    }

    protected function callAction($action, $params = [])
    {
        list($controller, $method) = $action;

        if (!class_exists($controller)) {
            throw new \Exception("Controller {$controller} not found");
        }

        $controllerInstance = new $controller();
        if (!method_exists($controllerInstance, $method)) {
            throw new \Exception("Method {$method} not found in controller {$controller}");
        }

        return $controllerInstance->$method(...$params);
    }
}
